package service;


import dao.UserDao;
import dao.domain.User;
import dao.impl.UserDaoImpl;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.Objects;

/**
 * @author gzb
 * UserDao是所有的使用者父类
 * 所有用户都能搜索并列出书籍
 * @Date 2023/9/19
 */
public class UserService {
    private static final UserDao USER_DAO = new UserDaoImpl();

    /**
     * 登录
     *
     * @param user:数据库表的名称，一般要使用的类类名一致
     * @param account:账号
     * @param password:密码
     * @return UserDao
     */
    public static User login(String user, String account, String password) throws SQLException {
        return USER_DAO.login(user, account, password);
    }

    /**
     * 从Cookie中获取账号名称
     *
     * @param request：前端发来的请求
     * @return 用户名称
     */
    public static String getAccountFromCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String account = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (Objects.equals(cookie.getName(), "username")) {
                    account = cookie.getValue();
                }
            }
        }
        return account;
    }

    /**
     * 从Cookie中获取账号是用户还是管理员
     *
     * @param request：前端发来的请求
     * @return 用户名称
     */
    public static String getUserFromCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String account = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (Objects.equals(cookie.getName(), "user")) {
                    account = cookie.getValue();
                }
            }
        }
        return account;
    }

    /**
     * 只通过账号找数据
     *
     * @param user:表类型
     * @param account：账号
     */
    public static User selectByAccount(String user, String account) throws SQLException {
        return USER_DAO.selectByAccount(user, account);
    }


}
